package main

import (
	"encoding/binary"
	"fmt"
	"net"
)

func runServer() {
	listen, err := net.Listen("tcp", ":48888")
	if err != nil {
		fmt.Printf("监听端口失败 err:%v", err.Error())
		return
	}
	defer func() {
		err := listen.Close()
		if err != nil {
			return
		}
	}()
	for {
		conn, err := listen.Accept()
		if err != nil {
			fmt.Printf("建立链接失败 err:%v", err.Error())
			continue
		}
		go handleConnection(conn)
	}
}

func handleConnection(conn net.Conn) {
	defer func() {
		conn.Close()
	}()
	for  {
		bytes,err:=receive(conn)
		if err!=nil {
			fmt.Println(err)
			return
		}
		err=jsonHandle(conn,bytes)
		if err!=nil {
			resHandle(conn,1,fmt.Sprintf("%v",err))
		}

	}

}


func receive(conn net.Conn)([]byte,error)  {
	var cmdLen int32
	err:=binary.Read(conn,binary.LittleEndian,&cmdLen)
	if err!=nil{
		return nil,err
	}
	b:=make([]byte, cmdLen)
	_,err =conn.Read(b)
	if err!=nil{
		return nil,err
	}
	return b,nil
}
func replyHandle(conn net.Conn,bytes []byte){

	err:=binary.Write(conn,binary.LittleEndian, int32(len(bytes)))
	if err!=nil{
		fmt.Println("链接断开 err",err)
		return
	}
	_,err =(conn).Write(bytes)
	if err!=nil{
		fmt.Println("链接断开 err",err)
		return
	}
}